//
//  Sender.m
//  ImageTransfer
//
//  Created by ly on 13-7-8.
//  Copyright (c) 2013年 Lei Yan. All rights reserved.
//

#import "Sender.h"
#import "AsyncSocket.h"

#define  SENDING_TAG        10000
@interface Sender () <AsyncSocketDelegate>
@property (nonatomic, assign) NSInteger tags;
@end

@implementation Sender
{
    AsyncSocket *asyncSocket;
}

- (id)init
{
    NSAssert(1==0, @"使用 initWithPort: 初始化");
    return nil;
}
- (id)initWithRemoteAddress:(NSString *)address onPort:(UInt16)port
{
    self = [super init];
    if (self) {
        self.remoteAddress = address;
        self.remotePort    = port;
        
        asyncSocket = [[AsyncSocket alloc] initWithDelegate:self];
        self.readData = [NSMutableData data];
//        self.urlData  = [NSData data];
        
        [asyncSocket connectToHost:self.remoteAddress onPort:self.remotePort error:nil];
    }
    return self;
}

- (void)sendData:(NSData *)data withFileName:(NSString *)fieName
{
//    if ( [self connectToRemote] )
//    {
        NSMutableData *mData = [NSMutableData data];
        
        NSDictionary *info = @{@"fname" : fieName};
        NSData *infoData = [NSJSONSerialization dataWithJSONObject:info options:NSJSONWritingPrettyPrinted error:nil];
        short int te = infoData.length + 6;
        
        const int first = 0x01;
        NSMutableData *fData = [NSMutableData dataWithBytes:&first length:1];
        [mData appendData:fData];
        
        NSMutableData *sData = [self changeDataHeightToLow:[NSData dataWithBytes:&te length:2]];
        [mData appendData:sData];
        
        const int third = 0x01;
        NSMutableData *tData = [NSMutableData dataWithBytes:&third length:1];
        [mData appendData:tData];
        
        short int random = 20;
        NSMutableData *foData = [self changeDataHeightToLow:[NSMutableData dataWithBytes:&random length:2]];
        [mData appendData:foData];
        [mData appendData:infoData];
        
    self.tags = SENDING_TAG;
        [asyncSocket writeData:mData withTimeout:-1 tag:SENDING_TAG];

 //   }
}

- (void)sendData:(NSData *)data
{
//    if ( [self connectToRemote] )
//    {
//
   
        NSMutableArray *arr = [self dealData:data];
        for (int i = 0; i < arr.count; i++) {
            if (i == 0) {
                //第一包
                
                NSMutableData *mData = [NSMutableData data];
                
                NSData *infoData = arr[i];
                short int te = infoData.length + 7;
                
                const int first = 0x02;
                NSMutableData *fData = [NSMutableData dataWithBytes:&first length:1];
                [mData appendData:fData];
                
                NSMutableData *sData = [self changeDataHeightToLow:[NSData dataWithBytes:&te length:2]];
                [mData appendData:sData];
                
                const int third = 0x01;
                NSMutableData *tData = [NSMutableData dataWithBytes:&third length:1];
                [mData appendData:tData];
                
                short int random = 20;
                NSMutableData *foData = [self changeDataHeightToLow:[NSMutableData dataWithBytes:&random length:2]];
                [mData appendData:foData];
                
                //收尾包
                const int fifth = 0x00;
                NSMutableData *bagData = [NSMutableData dataWithBytes:&fifth length:1];
                [mData appendData:bagData];
                
                [mData appendData:infoData];
                self.tags = 2000;
                [asyncSocket writeData:mData withTimeout:-1 tag:2000];
                
                
                
            } else if (i == arr.count - 1) {
                //最后一包
                
                NSMutableData *mData = [NSMutableData data];
                
                NSData *infoData = arr[i];
                short int te = infoData.length + 7;
                
                const int first = 0x02;
                NSMutableData *fData = [NSMutableData dataWithBytes:&first length:1];
                [mData appendData:fData];
                
                NSMutableData *sData = [self changeDataHeightToLow:[NSData dataWithBytes:&te length:2]];
                [mData appendData:sData];
                
                const int third = 0x01;
                NSMutableData *tData = [NSMutableData dataWithBytes:&third length:1];
                [mData appendData:tData];
                
                short int random = 20;
                NSMutableData *foData = [self changeDataHeightToLow:[NSMutableData dataWithBytes:&random length:2]];
                [mData appendData:foData];
                
                //收尾包
                const int fifth = 0x02;
                NSMutableData *bagData = [NSMutableData dataWithBytes:&fifth length:1];
                [mData appendData:bagData];
                
                [mData appendData:infoData];
                self.tags = 2002;
                [asyncSocket writeData:mData withTimeout:-1 tag:2002];
                
            }else {
                NSMutableData *mData = [NSMutableData data];
                
                NSData *infoData = arr[i];
                short int te = infoData.length + 7;
                
                const int first = 0x02;
                NSMutableData *fData = [NSMutableData dataWithBytes:&first length:1];
                [mData appendData:fData];
                
                NSMutableData *sData = [self changeDataHeightToLow:[NSData dataWithBytes:&te length:2]];
                [mData appendData:sData];
                
                const int third = 0x01;
                NSMutableData *tData = [NSMutableData dataWithBytes:&third length:1];
                [mData appendData:tData];
                
                short int random = 20;
                NSMutableData *foData = [self changeDataHeightToLow:[NSMutableData dataWithBytes:&random length:2]];
                [mData appendData:foData];
                
                //收尾包
                const int fifth = 0x01;
                NSMutableData *bagData = [NSMutableData dataWithBytes:&fifth length:1];
                [mData appendData:bagData];
                
                [mData appendData:infoData];
                self.tags = 2001;
                [asyncSocket writeData:mData withTimeout:-1 tag:2001];
                
            }
        }
        

    //   }
}
//------------------------------切分数据
- (NSMutableArray *)dealData:(NSData *)data {
    NSMutableArray *mArr = [NSMutableArray arrayWithCapacity:1];
    NSInteger leath;
    for (int i = 0; i < data.length; i+= 999) {
        leath = data.length - i;
        
        if (leath >= 999) {
            NSData *sData = [data subdataWithRange:NSMakeRange(i,999)];
            [mArr addObject:sData];
            
        }else {
            NSData *sData = [data subdataWithRange:NSMakeRange(i, leath)];
            [mArr addObject:sData];
            
        }
        
    }
    return mArr;
}

- (BOOL)connectToRemote
{
    BOOL success = YES;
    NSError *error = nil;
    if ( ![asyncSocket connectToHost:self.remoteAddress onPort:self.remotePort error:&error] )
    {
        success = NO;
        NSLog(@"Could not connet to %@:%d", self.remoteAddress, self.remotePort);
    }
    if (error)
    {
        success = NO;
        NSLog(@"%@", error);
    }
    return success;
}

#pragma mark - Delegate
- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
    NSLog(@"Socket disconnect with error:\n%@\n", err);
}

- (void)onSocketDidDisconnect:(AsyncSocket *)sock
{
}

- (void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket
{
    NSLog(@"Accept new socket: %@:%u", newSocket.connectedAddress, newSocket.connectedPort);
}

- (BOOL)onSocketWillConnect:(AsyncSocket *)sock
{
    return YES;
}

- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
    NSLog(@"Socket did Connect to host: %@:%u", host, port);

    double delayInSeconds = 1.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        NSUInteger length = sizeof(NSUInteger);
        NSMutableData *buffer = [NSMutableData data];
        [asyncSocket readDataToLength:length withTimeout:-1 buffer:buffer bufferOffset:0 tag:10000];
    });

}

- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag
{
    NSLog(@"Socket write data with tag: %ld\n %@", tag, sock.runLoopModes);
    
    [asyncSocket readDataWithTimeout:-1 tag:tag];


}

- (void)onSocket:(AsyncSocket *)sock didWritePartialDataOfLength:(NSUInteger)partialLength tag:(long)tag
{
    NSLog(@"Socket write data with tag: %ld\npartialLength: %u\n", tag, partialLength);

}

-(void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    
    // 对得到的data值进行解析与转换即可
    
    NSLog(@"llllllllll === %@--- %ld", data, tag);
        NSData *contentdata = [data subdataWithRange:NSMakeRange(6, data.length - 6)];

    
    if (tag == 10000) {
        [asyncSocket readDataWithTimeout:-1 tag:0];

        [self.readData appendData:contentdata];
//        NSLog(@"======%@", self.urlData);
        [self sendData:self.urlData];

    } else if (tag == 0) {
        [self.readData appendData:data];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:self.readData
                             
                                                            options:NSJSONReadingMutableContainers
                             
                                                              error:nil];
        NSLog(@"%s", [self.urlData bytes]);
        NSLog(@"oooooooo == %@", dic[@"code"]);
        NSString *resultStr = dic[@"code"];
            if ([self.Delegate respondsToSelector:@selector(sendrDateFirst)])
                [self.Delegate sendrDateFirst];
        
    }
    
    

}
- (void)onSocket:(AsyncSocket *)sock didReadPartialDataOfLength:(NSUInteger)partialLength tag:(long)tag
{
    
    
}

//-------------------------------高低位转换
- (NSMutableData *)changeDataHeightToLow:(NSData *)data {
    const char *bytes = [data bytes];
    NSMutableData *mData = [NSMutableData data];
    NSUInteger lenth = [data length];
    for (NSUInteger i = lenth; i > 0; i--) {
        [mData appendBytes:&bytes[i - 1] length:1];
    }
    return mData;
}

@end
